package com.lihui.demo;

import com.lihui.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * 功能描述
 *
 * @author wileda
 * @date 2022/12/28  15:43
 */
public class UpdateDemo{
    public static void main(String[] args) throws SQLException {
        //定义数据库操作中用到的资源变量
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;



        try {
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入学生Id：");
            int id = scanner.nextInt();
            System.out.println("请输入学号：");
            String sn = scanner.next();
            System.out.println("请输入姓名：");
            String name = scanner.next();
            System.out.println("请输入邮箱：");
            String mail = scanner.next();
            System.out.println("请输入班级编号：");
            int classesId = scanner.nextInt();
            //获取数据库连接
            connection = DBUtil.getConnection();
            //手动提交事务
            connection.setAutoCommit(false);
            //构造sql语句
            String sql = "update student set sn = ?,name = ?,qq_mail = ?,classes_id = ? where id = ?";
            //获取预处理对象
            statement = connection.prepareStatement(sql);
            statement.setString(1,sn);
            statement.setString(2,name);
            statement.setString(3,mail);
            statement.setInt(4,classesId);
            statement.setInt(5,id);

            int result = statement.executeUpdate();
            if(result > 0){
                System.out.println("修改学生信息成功");
            }else {
                System.out.println("修改失败");
            }
            //提交事务
            connection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            connection.rollback();
        }finally {
            DBUtil.close(null,statement,connection);
        }
    }
}
